package com.ruoyi.quartz.task;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.service.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.MoneyUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.payment.dongwopay.DongWoPayUtils;
import com.ruoyi.common.utils.payment.pbqzpay.PubuPayUtils;
import com.ruoyi.common.utils.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 定时任务调度测试
 *
 * @author admin
 */
@Component("dongwoOrderCheckTask")
public class DongwoOrderCheckTask {
    @Resource
    private ITOrderInfoService orderService;
    @Resource
    private ITRecipientInfoService userRecipientService;
    @Resource
    private ChargeService chargeService;
    @Resource
    private LoginService loginService;
    private Log logger = Log.get();

    @Autowired
    private ITSmjGoodListService itSmjGoodListService;

    @Autowired
    private ITSmjMachineListService itSmjMachineListService;

    @Autowired
    private ITSmjOrderInfoService itSmjOrderInfoService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 检查支付超时的订单。状态为待支付并且当前时间已经超过有效时间
     */
    public void checkOrder() throws Exception {
//        logger.info("CXZF订单查询..");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TOrderInfo query = new TOrderInfo();
//        query.setChannelType("alipay");
        query.setChannel("alipay_dongwo");
        query.setStatus(1);
        String newdateTime = DateUtils.dealDate("10分钟前");
//        String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        query.getParams().put("beginCreateTime", newdateTime);
        List<TOrderInfo> orderInfos = orderService.selectTOrderInfoListByNoAuth(query);
        for (TOrderInfo orderInfo : orderInfos) {
            synchronized (this) {
                if (orderInfo.getValidTime().before(new Date()) || StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
                    continue;
                }

                TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
                String accountJson = userRecipientInfo.getAccountJson();
                JSONObject accountObj = JSONObject.parseObject(accountJson);
                String token = accountObj.getString("ck");
                HashMap<String, String> headerMap = new HashMap();
                headerMap.put("Authorization","Bearer "+token);
                headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 17_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 appId=com.daimao.dongwo");
                JSONObject  reqOrderObj  = new JSONObject(true);
                long time = System.currentTimeMillis();
                String version = "2.0.18";
                //获取shopid
                reqOrderObj.put("payAmount",MoneyUtil.fenToYuan(orderInfo.getMoney()+""));
                reqOrderObj.put("orderId",orderInfo.getPay3rdOrderNo());
                String sign = DongWoPayUtils.getSign(time,"/easyhome-app-application/shop/order/assignOrderStatus",version,reqOrderObj);
                String qryOrderUrl = "https://gateway.jrdaimao.com/easyhome-app-application/shop/order/assignOrderStatus?requestTime="+time+"&dwSign="+sign+"&dwrsv="+version;
                logger.info("查单 请求地址:{}，请求参数：{}",qryOrderUrl,reqOrderObj.toJSONString());

                String qryOrderRes = HttpUtils.sendJsonMessage(qryOrderUrl,headerMap,reqOrderObj.toJSONString());
                JSONObject  qryOrderResObj = JSONObject.parseObject(qryOrderRes);
                logger.info("qryOrderUrl 返回：{}",qryOrderResObj.toJSONString());
                if(qryOrderResObj.getIntValue("code")==200){
                    if(qryOrderResObj.getBooleanValue("data")){
                        MsgPayResult msgPayResult = new MsgPayResult();
                        msgPayResult.setChannel(orderInfo.getChannel());
                        msgPayResult.setTradeNo(orderInfo.getId().toString());
                        msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                        msgPayResult.setOrderId(orderInfo.getPay3rdOrderNo());
                        msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                        msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                        msgPayResult.setChannelPayMsgResult(qryOrderResObj.toJSONString());
                        ResponseData responseData = chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                        chargeService.notifyUserPaySucc(orderInfo.getId());
                        logger.info("洞窝订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney() + " 处理结果：{}", responseData.getSuccess());
                    }

                }



            }
        }
    }

}
